// @algorithm @lc id=100315 lang=javascript
// @title er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof

/**
 * @param {number[]} postorder
 * @return {boolean}
 */
var verifyPostorder = function (postorder) {
  let pre = -1;
  const inorder = (nums, l, r) => {
    if (l > r) return true;
    let index = l;
    // 找到右子树的第一个节点
    while (nums[index] < nums[r]) index++;
    if (!inorder(nums, l, index - 1)) return false;
    if (pre !== -1 && nums[pre] > nums[r]) return false;
    pre = r;
    if (!inorder(nums, index, r - 1)) return false;
    return true;
  };
  return inorder(postorder, 0, postorder.length - 1);
};
